import './index.less';
import './icon.css';

import {observer} from "mobx-react/index";
import {WeaDialog, WeaRightMenu, WeaMoreButton, WeaLocaleProvider,WeaAlertPage} from 'ecCom';
import {Button, Spin, Modal} from 'antd';
import * as mobx from "mobx";
import LogItem from './LogItem'


import WfForward from '../wf-forward/index';
import WfForwardBack from '../wf-forwardback/index'
import WFForwardStore from '../../stores/forwardStore';
import WfForwardBackStore from '../../stores/forwardBackStore';
import Submit from '../wf-batch-submit/index';
import replace from 'lodash/replace';
import './util';

const formatMultiLang = WeaLocaleProvider.formatMultiLang;
const getLabel = WeaLocaleProvider.getLabel;

@observer
export default class Main extends React.Component {

    constructor(props) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        const wfForwardStore = new WFForwardStore();
        const wfForwardBackStore = new WfForwardBackStore();
        this.setState({
            wfForwardStore: wfForwardStore,
            wfForwardBackStore : wfForwardBackStore
        });
    }

    render() {
        const {wfForwardStore,wfForwardBackStore} = this.state;
        const {wfCenterLogListStore, onCancel} = this.props;
        const {logList = [], loading, submitLoading, logCount = 0, commonParams = {}, variableMap, loadMore, controlVariableMap, doSubmit} = wfCenterLogListStore;
        const {requestnamenew = '',requestname = '', requestid = -1, isHideArea = '0', f_weaver_belongto_userid = '', f_weaver_belongto_usertype = '0' } = commonParams;
        const {urger = ''} = commonParams;
        let linkAction = `javaScript:openFullWindowForWfCenterRequest('/workflow/request/ViewRequestForwardSPA.jsp?requestid=${requestid}${urger=='1'?'&urger=1':''}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}&isovertime=')`;

        let reg = /<[^>]+>/g;
        let title = formatMultiLang(requestnamenew||requestname);
        title = replace(title,reg,'');
        let dialogTitle = <a className={'portal-workflow-center-dialog-title'} href={linkAction}
                             title={title} dangerouslySetInnerHTML={{__html: title}} onClick={urger=='1'?()=>{this.doClose()}:()=>{}}></a>;
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@z1vxq2`}
                onCancel={() => this.doClose()}
                title={dialogTitle}
                visible={variableMap.get('visible')}
                style={{width: 900, height: 500}}
                icon={'icon-coms-workflow'}
                iconBgcolor='#0079DE'
                buttons={this.getBottomButtons()}
                hasScroll
                layout={jQuery('#container')[0]}
            >
                <div className='portal-workflow-center'>
                    {isHideArea == '1' ?
                        <div className={'hide-log-list'}>
                            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@h34w1z`} icon="icon-coms-blank">
                                <div>
                                    <span style={{'display':'block'}}>{getLabel(385183,'此流程设置了意见区域不显示')}</span>
                                    <a style={{'marginTop':'10px','display':'block'}} href={linkAction}>{getLabel(385184,'点击此处打开流程表单')}</a>
                                </div>
                            </WeaAlertPage>
                        </div>
                        :
                        <div className='wf-sign-list'>
                            {
                                logList.map((logitem,ecindex) => {
                                    return (<LogItem ecId={`${this && this.props && this.props.ecId || ''}_LogItem@uy8gfe@${ecindex}`} {...commonParams}
                                                     isShowUserheadimg={true}
                                                     data={logitem}
                                                     store={wfCenterLogListStore}
                                                     forwardEvent={(destuserid) => this.doForward(destuserid)}/>)
                                })
                            }
                        </div>
                    }
                    {!loading && logCount > logList.length && isHideArea != '1' &&
                    <div className='ant-table-placeholder'>
                                <span className={'log-load-more'} onClick={() => loadMore()}>
                                    <span>{getLabel('82720',"加载更多")}</span>
                                    <i className={'icon-coms-down'}/>
                                </span>
                    </div>
                    }
                    {!loading && logCount == 0 && isHideArea != '1' &&
                    <div className='ant-table-placeholder' style={{borderBottom: 0}}>{getLabel('386163',"暂时没有数据")}</div>
                    }
                    {loading &&
                    <div className='ant-table-placeholder' style={{borderBottom: 0}}>
                        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ca5rph`}/>
                    </div>
                    }
                    {wfForwardStore &&
                    <WfForward ecId={`${this && this.props && this.props.ecId || ''}_WfForward@y0e3mc`} wfForwardStore={wfForwardStore}/>
                    }
                    {
                        wfForwardBackStore && < WfForwardBack ecId={`${this && this.props && this.props.ecId || ''}_WfForwardBack@vzmtph`}  wfForwardBackStore={wfForwardBackStore}/>
                    }
                    {variableMap.has('showSubmitDialog') && <Submit ecId={`${this && this.props && this.props.ecId || ''}_Submit@rc8cjk`}
                        visible={variableMap.get('showSubmitDialog') || false}
                        onSubmit={(remark = '') => doSubmit(remark, onCancel)}
                        loading={submitLoading}
                        onCancel={() => {
                            controlVariableMap('showSubmitDialog', false)
                        }}
                        onSubmitText={urger=='1' ? getLabel(21223,'督办') : ''}
                    />
                    }
                </div>
            </WeaDialog>
        )
    }

    getBottomButtons() {
        const {wfCenterLogListStore} = this.props;
        const {rightMenu = {}, commonParams = {}, loading = false, variableMap} = wfCenterLogListStore;
        const {rightMenus = []} = rightMenu;
        const {requestid = -1} = commonParams;
        let btnArr = [];
        rightMenus.map((m,ecindex) => {
            const {type, menuName, menuIcon, menuFun, isTop, isPortal} = m;
            if (isPortal) {
                let fn = menuFun.indexOf('this') >= 0 ? `${menuFun.split('this')[0]})` : menuFun;
                isTop == "1" && btnArr.length < 4 &&
                btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3flbpl@${ecindex}`} type="primary" disabled={loading} onClick={() => {
                    this.doRightBtnEvent(fn)
                }}>{menuName}</Button>);
            }
        });
        btnArr.push(<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@7lpm46@more`}
            datas={this.getRightButtons()}
            collectParams={{
                favname: variableMap.get('dialogTitle'),
                favouritetype: "2",
                objid: requestid
            }}>{getLabel(17499,'更多')}</WeaMoreButton>)
        return btnArr;
    }

    getRightButtons() {
        const {wfCenterLogListStore} = this.props;
        const {rightMenu = {}, commonParams = {}, loading = false} = wfCenterLogListStore;
        const {rightMenus = []} = rightMenu;
        let btnArr = [];
        mobx.toJS(rightMenus).map((m, i) => {
            const {type, menuName, menuIcon, menuFun, isTop, isPortal} = m;
            if (isPortal) {
                let fn = menuFun.indexOf('this') >= 0 ? `${menuFun.split('this')[0]})` : menuFun;
                btnArr.push({
                    key: `${type}_${i}`,
                    disabled: loading,
                    icon: <i className={menuIcon}/>,
                    content: menuName,
                    onClick: () => {
                        this.doRightBtnEvent(fn)
                    }
                })
            }
        });
        return btnArr;
    }

    doRightBtnEvent(fn = '') {
        const {wfCenterLogListStore} = this.props;
        const {submitParam = {}, rightMenu = {}, controlVariableMap, commonParams = {}} = wfCenterLogListStore;
        const {required = false} = commonParams;
        if ("doReviewE9()" === fn) {
            this.doForward();
        } else if ("doSubmitBack()" === fn) {
            if (required) {
                this.doFormRequiredPrompt();
                return;
            }
            controlVariableMap('showSubmitDialog', true);
            controlVariableMap('submitParam', {actiontype: "requestBatchSubmit", src: "submit", needwfback: "1"});
        } else if ("doSubmitNoBack()" === fn) {
            if (required) {
                this.doFormRequiredPrompt();
                return;
            }
            controlVariableMap('showSubmitDialog', true);
            controlVariableMap('submitParam', {actiontype: "requestBatchSubmit", src: "submit", needwfback: "0"});
        } else if ("doRemark_nBack()" === fn) {
            controlVariableMap('showSubmitDialog', true);
            controlVariableMap('submitParam', {actiontype: "remarkOperation", src: "save", needwfback: "1"});
        } else if ("doRemark_nNoBack()" === fn) {
            controlVariableMap('showSubmitDialog', true);
            controlVariableMap('submitParam', {actiontype: "remarkOperation", src: "save", needwfback: "0"});
        } else if ("doSubmitDirect()" == fn) {
            if (required) {
                this.doFormRequiredPrompt();
                return;
            }
            const {ifchangstatus} = submitParam;
            const {hasback, hasnoback, lastnodeid} = rightMenu;
            if (ifchangstatus != "" && (hasback == "1" || (hasback == "" && hasnoback == ""))) {
                // doSubmitBack();
                controlVariableMap('showSubmitDialog', true);
                controlVariableMap('submitParam', {actiontype: "requestBatchSubmit", src: "submit", needwfback: "1"});
            } else {
                // doSubmitNoBack();
                controlVariableMap('showSubmitDialog', true);
                controlVariableMap('submitParam', {actiontype: "requestBatchSubmit", src: "submit", needwfback: "0"});
            }
        } else if ("doSupervise()" === fn) {
            controlVariableMap('showSubmitDialog', true);
            controlVariableMap('submitParam', {actiontype: "doSupervise", src: "supervise", needwfback: "0"});
            controlVariableMap('isSupervise', true);
        } else if("doReviewE9Back();" === fn){
            this.doForwardBack();
        }
    }

    doFormRequiredPrompt() {
        Modal.warning({
            title: getLabel(131329, '信息确认'),
            content: getLabel(386175, '表单有可必填字段，请打开表单填写后提交！'),
            okText: getLabel(83446, '确定')
        });
    }

    doForward(destuserid = '') {
        const {wfCenterLogListStore} = this.props;
        const {commonParams = {}, reloadLogList,loadFormRigthMunu} = wfCenterLogListStore;
        const {requestid = -1,nodeid,workflowid,beagenter='',f_weaver_belongto_userid,f_weaver_belongto_usertype} = commonParams;
        const {wfForwardStore} = this.state;
        const callBackActions = {
            'callBackfun': ()=>{
                reloadLogList();
                loadFormRigthMunu();
            }
        };
        const forwardParams = {
            requestid,
            nodeid,
            showForward: true,
            forwardflag: "1",
            forwardOperators: destuserid,
            bdf_wfid:workflowid,
            workflowid:workflowid,
            agentorbyagentid:beagenter,
            f_weaver_belongto_userid:f_weaver_belongto_userid,
            f_weaver_belongto_usertype:f_weaver_belongto_usertype
        };
        wfForwardStore.setShowForward(forwardParams, callBackActions);
    }

    /**
     * 转发收回
     */
    doForwardBack() {
        const {wfCenterLogListStore} = this.props;
        const {commonParams = {},  reloadLogList,loadFormRigthMunu} = wfCenterLogListStore;
        const {requestid = -1} = commonParams;
        const {wfForwardBackStore} = this.state;

        wfForwardBackStore.setShowForwardBack(true, requestid);
        wfForwardBackStore.setCallBackAction({
            callbackFun : ()=>{
                wfForwardBackStore.setShowForwardBack(false);
                reloadLogList();
                loadFormRigthMunu();
            }
        });
    }

    doClose() {
        const {wfCenterLogListStore, onCancel} = this.props;
        const {controlVariableMap, clearDatas} = wfCenterLogListStore;
        controlVariableMap('visible', false);
        clearDatas();
        try{
            typeof onCancel === 'function' && onCancel(false);
        }catch (e) {}
    }
}